<script setup lang="ts">
import {
  ElButton,
  ElTable,
  ElTableColumn,
  ElInput,
  ElInputNumber,
  TableColumnCtx
} from 'element-plus'
import 'element-plus/es/components/icon/style/css'
import 'element-plus/es/components/input/style/css'
import 'element-plus/es/components/button/style/css'
import 'element-plus/es/components/tag/style/css'
import 'element-plus/es/components/menu/style/css'
import 'element-plus/es/components/menu-item/style/css'
import { PropType, reactive, ref, watch, h } from 'vue'
import { useTableDialogStore } from '@/store/modules/purchaseTableDialog'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useForm } from '@/hooks/web/useForm'
import { getOrderSelectApi, getProductSelectApi } from '@/api/purchase'

const { formMethods } = useForm()
const { getFormData, getElFormExpose } = formMethods

const { push } = useRouter()
type tableDataType = {
  id: number
  cname: string
  code: string
  style_code: string
  unit: string
  num: number
  unit_price: number
  unit_sum: number
  notes: string
}

interface SummaryMethodProps<T = tableDataType> {
  columns: TableColumnCtx<T>[]
  data: T[]
}

const props = defineProps({
  tableDialogStoreID: {
    type: String,
    default: ''
  },
  tableDialogCurdSchema: {
    type: Array as PropType<CrudSchema[]>, // 明确类型为 CrudSchema[]
    default: () => [] // 设置默认值为一个空数组
  },
  modelValue: {
    type: Array as PropType<tableDataType[]>,
    default: () => []
  },
  disabled: {
    type: Boolean,
    default: () => false
  },
  setValues: {
    type: Function,
    default: () => {}
  }
})

// 挂载完成时触发
// onMounted(() => {
//   console.log(tableData.value, 888)
//   // console.log(props.modelValue, 888)
// })

const emit = defineEmits(['update:modelValue'])

const tableDialogStore = useTableDialogStore(props.tableDialogStoreID)
const { allSchemas } = useCrudSchemas(
  props.tableDialogCurdSchema ? props.tableDialogCurdSchema : []
)
const tableData = ref<tableDataType[]>([])

const addEmptyRow = () => {
  tableDialogStore.selectedItems = []
  tableDialogStore.openDialog()
  tableDialogStore.setSchema(allSchemas)
}

const rowClassName = ({ row }) => (row.editing ? 'editing-row' : '')
const editCell = (row) => {
  row.editing = true
}

const submit = async () => {
  const elForm = await getElFormExpose()
  const valid = await elForm?.validate().catch((err) => {
    console.log('err', err)
  })
  if (valid) {
    const formData = await getFormData()
    formData.pid = tableDialogStore.selectedItems.map((item) => item.id).join(',')
    return formData
  }
}

const action = (row: any) => {
  push(`/purchase/payment-order-management/detail?id=${row.id}`)
}

defineExpose({
  submit
})

tableDialogStore.dialogSubmit = () => {
  const existingIds = new Set(tableData.value.map((item) => item.id))
  tableDialogStore.selectionRow.forEach((item) => {
    if (!existingIds.has(item.id)) {
      tableData.value.push({
        id: item.id,
        cname: item.cname,
        code: item.code,
        style_code: item.style_code,
        unit: item.unit_value,
        num: 0,
        unit_price: 0,
        unit_sum: 0,
        notes: ''
      })
    }
  })
}
const unitSums = reactive({})
const isDisabled = ref(props.disabled)
const order_no = ref<string>()

const orderList = ref<Array<Record<string, any>>>([])
const selectLoading = ref<boolean>(false)

/**
 * 获取订单列表
 * @param value
 */
const getOrderOptions = async (value) => {
  if (value) {
    selectLoading.value = true
    const userResp = await getOrderSelectApi({ order_no: value })
    orderList.value = userResp.data
    selectLoading.value = false
  }
}

const getSummaries = (param: SummaryMethodProps) => {
  const needHandleColumns = ['num', 'unit_price', 'unit_sum']
  // const needShowMoney = ['unit_price', 'unit_sum']
  const needShowMoney: string[] = []
  const { columns, data } = param
  const sums: string[] = []
  let pay_amount = 0
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index.toString()] = h('div', { style: { textDecoration: 'underline' } }, ['Total Cost'])
      return
    }
    const values = data.map((item) => Number(item[column.property]))
    if (
      !values.every((value) => Number.isNaN(value)) &&
      needHandleColumns.includes(column.property)
    ) {
      sums[index] = `${needShowMoney.includes(column.property) ? '¥' : ''} ${values.reduce(
        (prev, curr) => {
          const value = Number(curr)
          if (!Number.isNaN(value)) {
            return prev + curr
          } else {
            return prev
          }
        },
        0
      )}`
    } else {
      sums[index] = 'N/A'
    }

    if (column.property == 'unit_sum') {
      pay_amount = values.reduce((prev, curr) => {
        const value = Number(curr)
        if (!Number.isNaN(value)) {
          return prev + curr
        } else {
          return prev
        }
      }, 0)
    }
  })
  props.setValues({
    product_total_amount: pay_amount
  })
  return sums
}

watch(
  tableData,
  (newTableData) => {
    // 清空 unitSums
    Object.keys(unitSums).forEach((key) => delete unitSums[key])

    // 更新 unitSums
    newTableData.forEach((row, index) => {
      unitSums[index] = row.num * row.unit_price
      row.unit_sum = row.num * row.unit_price
    })
    // 更新表单数据
    emit('update:modelValue', newTableData)
  },
  { deep: true }
)

watch(
  () => props.modelValue,
  (val: any) => {
    tableData.value = val
  },
  {
    deep: true,
    immediate: true
  }
)
console.log(tableData.value, 89)
</script>

<template>
  <div>
    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 10px"
      :row-class-name="rowClassName"
      @cell-click="editCell"
    >
      <el-table-column prop="payno" label="付款单编号" width="180">
        <template #default="{ row }">
          
          <el-link :underline="false" type="primary" @click="action(row)">
            <span>{{ row.payno }}</span>
          </el-link>
          
        </template>
      </el-table-column>
      <!-- <el-table-column prop="payable_amount" label="应付款金额">
        <template #default="{ row }">
          <span>{{ row.payable_amount }}</span>
        </template>
      </el-table-column> -->
      <el-table-column prop="pay_amount" label="已付款金额">
        <template #default="{ row }">
          <span>{{ row.pay_amount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="payment_date" label="付款日期">
        <template #default="{ row }">
          <span>{{ row.payment_date }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="pay_type_value" label="付款方式">
        <template #default="{ row }">
          <span>{{ row.pay_type_value }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="payment_account_value" label="付款账户">
        <template #default="{ row }">
          <span>{{ row.payment_account_value }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="status_value" label="付款单状态">
        <template #default="{ row }">
          <span>{{ row.status_value }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="unit" label="交易单号">
        <template #default="{ row }">
          <span>{{ row.unit }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="responsible_value" label="负责人">
        <template #default="{ row }">
          <span>{{ row.responsible_value }}</span>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<style scoped>
.editing-row {
  background-color: #f5f7fa;
}
</style>
